package com.mfh.auto.create.mvvm.autocreatemvvm.file

import com.intellij.openapi.fileTypes.FileType
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiFileFactory
import com.mfh.auto.create.mvvm.autocreatemvvm.executeCouldRollBackAction
import com.mfh.auto.create.mvvm.autocreatemvvm.filetype.KotlinFileType
import com.mfh.auto.create.mvvm.autocreatemvvm.utils.CreateFileUtils

abstract class BaseFileModel {

    /**
     * 构建文件名称
     */
    abstract fun buildFileName(): String

    /**
     * 构建文件内容
     */
    abstract fun buildContentString(directory: PsiDirectory): String

    /**
     * 获取文件类型
     */
    open fun getFileType(): FileType = KotlinFileType()

    /**
     * 创建文件
     */
    open fun createFile(directory: PsiDirectory) {
        val psiFileFactory = PsiFileFactory.getInstance(directory.project)
        executeCouldRollBackAction(directory.project) {
            val file = psiFileFactory.createFileFromText(
                buildFileName(),
                KotlinFileType(),
                buildContentString(directory)
            )
            try {
                directory.add(file)
            } catch (e: Exception) {
            }
        }
    }

    /**
     * 获取项目包名
     */
    protected fun getProjectPackage(directory: PsiDirectory): String {
        var dir: PsiDirectory = directory
        var result = ""
        while (dir.parent != null && result.isEmpty()) {
            if ((dir.files.size + dir.subdirectories.size > 1)
                // 确保向上三级目录都是单文件夹,基本上可以覆盖大部分情况
                && (dir.parent!!.subdirectories.size + dir.parent!!.files.size == 1)
                && (dir.parent!!.parent?.subdirectories?.size == 1)
                && (dir.parent!!.parent?.parent?.subdirectories?.size == 1)
            ) {
                result = CreateFileUtils.getPackageByDirectory(dir)
            }
            dir = dir.parent!!
        }
        return result
    }
}